import 'dart:io';

import 'package:fluwx_no_pay/fluwx_no_pay.dart';

class WechatUtil{

  factory WechatUtil() => _getInstance();

  static WechatUtil get instance => _getInstance();

  static WechatUtil? _instance;

  WechatUtil._internal();

  static WechatUtil _getInstance(){
    _instance ??= WechatUtil._internal();
    return _instance!;
  }
  
  /*
  初始化
   */
  init(){
    registerWxApi(appId: "wxd930ea5d5a228f5f",universalLink: "https://your.univerallink.com/link/");
  }

  Future<bool> hasWeChat() async {
    return await isWeChatInstalled;
  }

  Future<bool> openWeChat() async {
    return await openWeChatApp();
  }

  /*
  微信登录, 获取code
   */
  Future<bool> login() async {
    weChatResponseEventHandler.listen((event) async {
      print(event);
      if (event is WeChatAuthResponse && event.errCode == 0) {// 支付成功
        WeChatAuthResponse response = event;
        response.code;
      }
    });
    return await sendWeChatAuth(scope: "snsapi_userinfo", state: "wechat_sdk_demo_test");
  }

  /*
    WeChatShareTextModel
    WeChatShareMiniProgramModel
    WeChatShareImageModel
    WeChatShareMusicModel
    WeChatShareVideoModel
    WeChatShareWebPageModel
    WeChatShareFileModel

    scene:
    [WeChatScene.SESSION]会话
    [WeChatScene.TIMELINE]朋友圈
    [WeChatScene.FAVORITE]收藏
   */
  Future<bool> shareText(String text) async {
    return await shareToWeChat(WeChatShareTextModel(text, scene: WeChatScene.SESSION));
  }

  /*
  WeChatImage.network(String source, {String suffix});
  WeChatImage.file(File source, {String suffix = ".jpeg"});
  WeChatImage.asset(String source, {String suffix});
  WeChatImage.binary(Uint8List source, {String suffix = ".jpeg"});
   */
  Future<bool> shareImage(String imgRes) async {
    return await shareToWeChat(WeChatShareImageModel(
      WeChatImage.file(File('fileName')),
      scene: WeChatScene.SESSION,
    ));
  }

  /*
  支付 https://github.com/OpenFlutter/fluwx/blob/master/doc/PAYMENT_CN.md
   */
  Future<bool> pay(Map<String, dynamic> result) async {
    weChatResponseEventHandler.listen((event) async {
      print(event);
      if (event is WeChatPaymentResponse && event.errCode == 0) {// 支付成功
        WeChatPaymentResponse response = event;
      }
    });
    return await payWithWeChat(
      appId: result['appid'],
      partnerId: result['partnerid'],
      prepayId: result['prepayid'],
      packageValue: result['package'],
      nonceStr: result['noncestr'],
      timeStamp: result['timestamp'],
      sign: result['sign'],
    );
  }
}